import { notification } from 'ant-design-vue';
import type { Router } from 'vue-router';
import http from '@/visual/commons/utils/axios-util';
import LogUtil from '@/visual/commons/utils/log-util';

const registerHttpInterceptor = (router: Router) => {
  http.interceptors.request.use(
    (config) => {
      const token = '';
      config.headers = {
        appToken: token,
      };

      LogUtil.info({
        moduleName: 'httpInterceptor ',
        msg: `${config.url}请求前的参数：`,
        data: config,
        prop: false,
      });

      return config;
    },
    (error) => {
      notification.error({
        message: '提示',
        description: error,
      });

      Promise.reject(error);
    }
  );

  http.interceptors.response.use(
    (response: any) => {
      LogUtil.info({
        moduleName: 'httpInterceptor',
        msg: '请求后返回的数据：',
        data: response,
        prop: false,
      });

      return response;
    },
    (error: any) => {
      const errorObj: any = JSON.parse(JSON.stringify(error));
      if (errorObj.response) {
        notification.error({
          message: '提示',
          description: '系统错误，状态码：' + errorObj.response.status,
        });
      } else {
        notification.error({
          message: '提示',
          description: '网络异常，请重试！',
        });
      }
      LogUtil.error({
        moduleName: 'httpInterceptor',
        msg: '请求错误数据：',
        data: error,
        prop: false,
      });
      return Promise.reject(error);
    }
  );
};

export default registerHttpInterceptor;
